<?php

/**
 * @author CHUN Dany <chundany@gmail.com>
 */
class Mod_Math extends CI_Model
{ 
  public function getMath($start, $num)
  {
      $this->db->select('*')
        ->select('s.id AS Ids')
        ->from(table('subject').' s')
        ->join(table('class').' c', 's.'.field('classId').'= c.'.field('id'))
        ->join(table('tbnswer').' A', 'A.'.field('questionId').'= s.'.field('id'))
        ->order_by('s.'.field('updatedAt'), 'DESC');
    $this->db->limit($num, $start);
    $query = $this->db->get();
    return $query;
  }
  
  public function getMathNum()
  {
    $objDb = $this->getAllMath();
    return $objDb->num_rows();
  }
  
  public function getAllMath() {
    $this->db->select('*')
        ->from(table('subject'))
        ->order_by(field('updatedAt'), 'DESC');
    return $this->db->get();
  }

  public function insert($image = NULL)
  {
    $data = array(
      field('question')    => $image,
      field('classId')     => $this->input->post('class')
    );
    $this->db->insert(table('subject'), $data); 
    //var_dump($data);
    return $this->db->affected_rows();
  }
  
  public function update($id, $image = NULL)
  {
    $data = array(
      field('question')    => $image,
      field('classId')     => $this->input->post('class')
    );
    $this->db->set(field('updatedAt'), 'NOW()', FALSE);
    if(empty($image)) unset($data[field('image')]);
    $this->db->where(field('id'),$id);
    $this->db->update(table('subject'), $data);
    return $this->db->affected_rows();
  }
  
  public function delete($id)
  {
    $this->db->set(field('deletedAt'), 'NOW()', FALSE);
    $this->db->where(field('id'), $id);
    $this->db->update(table('subject'));

    return $this->db->affected_rows();
  }

  public function getMathById($id)
  {
    $this->db->select('*')
        ->select('tbl_subject.id AS Ids')
        ->from(table('subject'))
        ->join('tbl_class', 'tbl_class.id = tbl_subject.class_id')
        ->where('tbl_subject.id', $id);
    $result = $this->db->get();
    return $result->row_array();
  }

  public function getClassList($id = NULL)
  {
    $this->db->select(field('id').', '.field('name'));
    $this->db->from(table('class'));
    $result = $this->db->get();
    $return = array('' => '');
    if($result->num_rows() > 0){
      foreach($result->result_array() as $row){
        $return[$row[field('id')]] = $row[field('name')];
      }
    }
    return $return;
  }
}